<template>
  <a-layout class="main-layout">
    <a-layout-header class="header">
      <div class="header-left">
        <div class="logo">
          <GlobalOutlined class="logo-icon" />
          <span class="logo-text">物流配送</span>
        </div>

        <!-- 顶部一级模块导航 -->
        <div class="top-menu">
          <div
            v-for="module in visibleModules"
            :key="module.key"
            :class="['menu-item', { active: selectedModule === module.key }]"
            @click="handleModuleChange(module.key)"
          >
            <component
              v-if="module.icon && iconComponents[module.icon]"
              :is="iconComponents[module.icon]"
              class="menu-icon"
            />
            {{ module.title }}
          </div>
        </div>
      </div>

      <div class="header-right">
        <!-- 当前站点信息（仅租户端显示） -->
        <div v-if="!userStore.isPlatformAdmin" class="site-info">
          <!-- 仅租户超级管理员可以切换站点/查看全部站点 -->
          <a-dropdown v-if="userStore.userInfo?.role === 'SUPER_ADMIN'">
            <a class="site-selector" @click.prevent>
              <EnvironmentOutlined class="site-icon" />
              <span class="site-name">{{
                currentSite?.siteName || "全部站点"
              }}</span>
              <DownOutlined class="dropdown-icon-small" />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item-group title="切换站点">
                  <a-menu-item
                    @click="handleSiteSwitch(null)"
                    :disabled="currentSite === null"
                  >
                    <GlobalOutlined />
                    全部站点
                    <CheckOutlined
                      v-if="currentSite === null"
                      style="margin-left: 8px; color: var(--primary-color)"
                    />
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item
                    v-for="site in siteList"
                    :key="site.id"
                    @click="handleSiteSwitch(site.id)"
                    :disabled="site.id === currentSite?.id"
                  >
                    <EnvironmentOutlined />
                    {{ site.siteName }}
                    <CheckOutlined
                      v-if="site.id === currentSite?.id"
                      style="margin-left: 8px; color: var(--primary-color)"
                    />
                  </a-menu-item>
                </a-menu-item-group>
              </a-menu>
            </template>
          </a-dropdown>
          <!-- 非超级管理员只显示站点名称 -->
          <div v-else-if="currentSite" class="site-display">
            <EnvironmentOutlined class="site-icon" />
            <span class="site-name">{{ currentSite.siteName }}</span>
          </div>
        </div>

        <!-- 用户账户下拉菜单 -->
        <a-dropdown>
          <a class="ant-dropdown-link user-account" @click.prevent>
            <a-avatar :size="32" :style="{ backgroundColor: '#6366f1' }">
              {{ userStore.userInfo?.realName?.charAt(0) || "U" }}
            </a-avatar>
            <div class="user-info">
              <div class="user-name">{{ userStore.userInfo?.realName }}</div>
              <div class="user-role">
                {{ getRoleDisplayName(userStore.userInfo?.role) }}
              </div>
            </div>
            <DownOutlined class="dropdown-icon" />
          </a>
          <template #overlay>
            <a-menu>
              <a-menu-item key="profile" @click="handleProfile">
                <UserOutlined />
                账户信息
              </a-menu-item>
              <a-menu-divider />
              <a-menu-item key="logout" @click="handleLogout">
                <LogoutOutlined />
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </a-layout-header>

    <div class="main-content-layout">
      <!-- 二级功能菜单 (左侧图标栏 102px) -->
      <div class="primary-menu">
        <div
          v-for="item in currentModuleMenus"
          :key="item.path"
          :class="[
            'primary-menu-item',
            { active: selectedKeys.includes(item.path) },
          ]"
          @click="handleMenuClick({ key: item.path })"
        >
          <div class="menu-item-title">
            <component
              :is="item.icon && iconComponents[item.icon as string] ? iconComponents[item.icon as string] : null"
              class="icon"
            />
            <span class="menu-item-title__title">{{ item.title }}</span>
          </div>
        </div>
      </div>

      <!-- 三级子功能菜单侧边栏 (116px) -->
      <div v-if="hasThirdLevelMenu" class="sub-menu">
        <div class="sub-menu-scroll">
          <a-menu
            v-model:selectedKeys="selectedThirdLevelKeys"
            v-model:openKeys="openThirdLevelKeys"
            mode="inline"
            @click="handleThirdLevelMenuClick"
          >
            <template v-if="currentThirdLevelMenus.length > 0">
              <a-sub-menu key="main-group">
                <template #title>{{ currentSecondLevelTitle }}</template>
                <a-menu-item
                  v-for="item in currentThirdLevelMenus"
                  :key="item.key"
                >
                  {{ item.title }}
                </a-menu-item>
              </a-sub-menu>
            </template>
          </a-menu>
        </div>
      </div>

      <div class="content">
        <div class="content-wrapper">
          <router-view />
        </div>
      </div>
    </div>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import {
  UserOutlined,
  LogoutOutlined,
  DownOutlined,
  EnvironmentOutlined,
  CheckOutlined,
  HomeOutlined,
  InboxOutlined,
  AppstoreOutlined,
  CarOutlined,
  SendOutlined,
  SettingOutlined,
  BookOutlined,
  SafetyOutlined,
  GlobalOutlined,
  ClockCircleOutlined,
  DatabaseOutlined,
  DollarOutlined,
  ShopOutlined,
  FileTextOutlined,
  TeamOutlined,
  DeploymentUnitOutlined,
  BarChartOutlined,
  UnorderedListOutlined,
} from "@ant-design/icons-vue";
import { useUserStore } from "@/stores/user";
import { getSiteList, switchSite } from "@/api/tenant/site";
import type { Site } from "@/types/site";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const selectedKeys = ref<string[]>([route.path]);
const selectedThirdLevelKeys = ref<string[]>([]);
const openThirdLevelKeys = ref<string[]>(["main-group"]); // 默认展开主分组
const selectedModule = ref<string>("collection");
const siteList = ref<Site[]>([]);
const currentSite = ref<Site | null>(null);

// 图标组件映射
const iconComponents: Record<string, any> = {
  // 二级功能图标
  HomeOutlined, // 工作台
  InboxOutlined, // 收货开票 - 改为 FileTextOutlined
  LoadingOutlined: AppstoreOutlined, // 装车管理使用应用图标
  SendOutlined, // 发车管理使用发送图标
  CarOutlined, // 车辆管理使用汽车图标
  UserOutlined, // 司机管理 - 改为 TeamOutlined
  SettingOutlined, // 系统设置
  BookOutlined, // 字典管理
  SafetyOutlined, // 安全相关
  // 重新分配的图标
  FileTextOutlined, // 收货开票专用
  TeamOutlined, // 司机管理专用
  UnorderedListOutlined, // 列表图标
  // 一级模块图标
  ContainerOutlined: ShopOutlined, // 集货中心使用商店图标
  DeliveredProcedureOutlined: DeploymentUnitOutlined, // 到货中心使用部署图标
  AccountBookOutlined: DollarOutlined, // 财务中心使用金钱图标
  PieChartOutlined: BarChartOutlined, // 数据中心使用柱状图图标
  // 通用图标
  EnvironmentOutlined, // 站点相关
  CheckOutlined, // 选中标记
  ClockCircleOutlined, // 时间相关
  AppstoreOutlined, // 应用图标
  ShopOutlined, // 商店图标
  DollarOutlined, // 金钱图标
  DatabaseOutlined, // 数据库图标
  DeploymentUnitOutlined, // 部署图标
  BarChartOutlined, // 柱状图图标
};

// 从路由配置中提取模块信息
const getAllModulesFromRouter = () => {
  const routes = router.getRoutes();
  const mainLayoutRoute = routes.find(
    (r) => r.path === "/" && r.meta?.requiresAuth
  );

  if (!mainLayoutRoute?.children) return [];

  return mainLayoutRoute.children
    .filter((route) => route.meta?.isModule)
    .map((route) => {
      const meta = route.meta as any;
      return {
        key: meta.moduleKey,
        title: meta.title,
        icon: meta.icon,
        roles: meta.roles || [],
        permission:
          typeof meta.permission === "string"
            ? meta.permission
            : meta.permission?.code,
        children: (route.children || [])
          .filter((child) => !child.meta?.hideInMenu && child.meta?.title)
          .map((child) => {
            const childPerm = (child.meta as any)?.permission;
            return {
              path: `/${route.path}/${child.path}`,
              title: child.meta?.title,
              icon: child.meta?.icon,
              permission:
                typeof childPerm === "string" ? childPerm : childPerm?.code,
              $actions: (child.meta as any)?.$actions as
                | Record<string, { title: string; code: string }>
                | undefined,
            };
          }),
      };
    });
};

// 根据用户角色过滤可见模块
const visibleModules = computed(() => {
  const userRole = userStore.userInfo?.role;
  if (!userRole) return [];

  const allModules = getAllModulesFromRouter();
  return allModules.filter((module) => {
    // 平台模块仅平台管理员可见
    if (module.key === "platform") return userStore.isPlatformAdmin;
    // 其余模块：无 roles 限制则默认对租户侧用户可见
    if (!module.roles || module.roles.length === 0) {
      // 如果模块有子页面，检查用户是否有任一子页面权限或操作权限
      if (module.children && module.children.length > 0) {
        // 检查子页面权限（只检查页面权限，不再检查操作权限）
        const childPerms = module.children
          .map((child) => child.permission)
          .filter((perm) => perm) as string[];
        if (childPerms.length > 0 && userStore.hasAnyPermission(childPerms)) {
          return !userStore.isPlatformAdmin;
        }
      }
      // 如果没有子页面或子页面都没有权限码，则检查模块权限码
      if (module.permission) {
        const modulePermCode =
          typeof module.permission === "string"
            ? module.permission
            : module.permission.code;
        if (modulePermCode && !userStore.hasPermission(modulePermCode)) {
          return false;
        }
      }
      return !userStore.isPlatformAdmin;
    }
    // 如果模块配置了权限码，先检查模块权限码
    const modulePermCode =
      typeof module.permission === "string"
        ? module.permission
        : module.permission?.code;
    if (modulePermCode && !userStore.hasPermission(modulePermCode)) {
      // 如果模块有子页面，再检查用户是否有任一子页面权限或操作权限
      if (module.children && module.children.length > 0) {
        // 检查子页面权限（只检查页面权限，不再检查操作权限）
        const childPerms = module.children
          .map((child) => child.permission)
          .filter((perm) => perm) as string[];
        if (childPerms.length > 0 && userStore.hasAnyPermission(childPerms)) {
          return true;
        }
      }
      return false;
    }
    // 若配置了 roles，则按配置判断
    return module.roles.includes(userRole);
  });
});

// 当前模块的菜单项
const currentModuleMenus = computed(() => {
  const allModules = getAllModulesFromRouter();
  const module = allModules.find((m) => m.key === selectedModule.value);
  if (!module) return [];

  // 过滤掉当前用户没有权限的二级菜单（必须要有页面权限才能显示）
  return module.children.filter((item) => {
    // 必须要有页面权限才能显示菜单项
    if (!item.permission) {
      return false;
    }

    // 检查页面权限（hasPermission 已支持原始权限码和 page_ 前缀格式）
    return userStore.hasPermission(item.permission);
  });
});

// 三级菜单相关
const hasThirdLevelMenu = computed(() => {
  // 根据当前二级菜单项是否有子路由来决定是否显示三级菜单
  const currentSecondLevelRoute = getCurrentSecondLevelRoute();
  if (
    !currentSecondLevelRoute?.children ||
    currentSecondLevelRoute.children.length === 0
  ) {
    return false;
  }
  // 检查是否至少有一个可见的子菜单（非hideInMenu）
  const hasVisibleChild = currentSecondLevelRoute.children.some(
    (child) => !child.meta?.hideInMenu
  );
  return hasVisibleChild;
});

const currentSecondLevelTitle = computed(() => {
  const currentSecondLevelRoute = getCurrentSecondLevelRoute();
  return currentSecondLevelRoute?.meta?.title || "";
});

const currentThirdLevelMenus = computed(() => {
  const currentSecondLevelRoute = getCurrentSecondLevelRoute();
  if (!currentSecondLevelRoute?.children) return [];

  return currentSecondLevelRoute.children
    .filter((child) => !child.meta?.hideInMenu)
    .map((child) => ({
      key: child.name as string,
      title: child.meta?.title || "",
      icon: child.meta?.icon || "",
      path: child.path,
    }));
});

// 获取当前二级路由配置
const getCurrentSecondLevelRoute = () => {
  const routes = router.getRoutes();
  const currentPath = route.path;

  // 直接从路由配置中找到匹配的路由
  for (const routeRecord of routes) {
    if (routeRecord.path === "/" && routeRecord.children) {
      for (const moduleRoute of routeRecord.children) {
        if (moduleRoute.children) {
          for (const childRoute of moduleRoute.children) {
            // 构建完整路径进行匹配
            const fullPath = `/${moduleRoute.path}/${childRoute.path}`.replace(
              /\/+/g,
              "/"
            );
            if (
              currentPath === fullPath ||
              currentPath.startsWith(fullPath + "/")
            ) {
              return childRoute;
            }
          }
        }
      }
    }
  }
  return null;
};

// 根据路径获取模块
const getModuleByPath = (path: string): string => {
  if (path.startsWith("/platform")) return "platform";
  if (path.includes("/settings")) return "settings";
  if (path.includes("/arrival")) return "arrival";
  if (path.includes("/finance")) return "finance";
  if (path.includes("/data")) return "data";
  return "collection";
};

// 获取父路由路径
const getParentRoutePath = (path: string): string | null => {
  // 例如: /tenant/dispatch/list -> /tenant/dispatch
  const pathSegments = path.split("/").filter(Boolean);
  if (pathSegments.length <= 2) return null;

  // 移除最后一段，重建父路径
  const parentSegments = pathSegments.slice(0, -1);
  return "/" + parentSegments.join("/");
};

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    selectedModule.value = getModuleByPath(newPath);

    // 获取当前二级路由和父路由
    const currentSecondLevelRoute = getCurrentSecondLevelRoute();
    const parentRoutePath = getParentRoutePath(newPath);

    // 设置选中的菜单项，包括父路由路径
    if (parentRoutePath && parentRoutePath !== newPath) {
      selectedKeys.value = [parentRoutePath, newPath];
    } else {
      selectedKeys.value = [newPath];
    }

    // 更新三级菜单选择状态
    if (
      currentSecondLevelRoute?.children &&
      currentSecondLevelRoute.children.length > 0
    ) {
      // 找到匹配当前路径的子路由
      const matchedChild = currentSecondLevelRoute.children.find((child) => {
        const childPath = child.path;
        return newPath.includes(childPath) || newPath.endsWith(childPath);
      });

      if (matchedChild) {
        selectedThirdLevelKeys.value = [matchedChild.name as string];
      } else {
        // 如果没有匹配的子路由，选中第一个非隐藏的子路由
        const firstVisibleChild = currentSecondLevelRoute.children.find(
          (child) => !child.meta?.hideInMenu
        );
        if (firstVisibleChild) {
          selectedThirdLevelKeys.value = [firstVisibleChild.name as string];
        }
      }
    } else {
      selectedThirdLevelKeys.value = [];
    }
  },
  { immediate: true }
);

// 大模块切换
const handleModuleChange = (moduleKey: string) => {
  selectedModule.value = moduleKey;
  const allModules = getAllModulesFromRouter();
  const module = allModules.find((m) => m.key === moduleKey);
  if (module) {
    if (module.children.length > 0) {
      // 找到用户有页面权限的第一个子路由
      const firstAccessibleChild = module.children.find((child) => {
        if (!child.permission) return false;
        return userStore.hasPermission(child.permission);
      });

      if (firstAccessibleChild) {
        router.push(firstAccessibleChild.path);
      } else {
        // 用户没有任何子页面权限，跳转到无权限页面
        router.push("/no-permission");
      }
    } else {
      // 模块暂无功能页面
      message.info(`${module.title}功能开发中，敬请期待...`);
    }
  }
};

// 菜单点击
const handleMenuClick = ({ key }: { key: string }) => {
  router.push(key);
};

// 三级菜单点击
const handleThirdLevelMenuClick = ({ key }: { key: string }) => {
  const currentSecondLevelRoute = getCurrentSecondLevelRoute();
  if (!currentSecondLevelRoute?.children) return;

  // 找到对应的子路由
  const targetChild = currentSecondLevelRoute.children.find(
    (child) => child.name === key
  );
  if (!targetChild) return;

  // 构建完整的路径
  const currentModule = getAllModulesFromRouter().find(
    (m) => m.key === selectedModule.value
  );
  if (!currentModule) return;

  const fullPath = `/${
    currentModule.children.find(
      (c) => c.title === currentSecondLevelRoute.meta?.title
    )?.path
  }/${targetChild.path}`.replace(/\/+/g, "/");

  // 跳转到目标路由
  router.push(fullPath);
};

// 加载站点列表
const loadSites = async () => {
  if (userStore.isPlatformAdmin) return;

  try {
    const res = await getSiteList();
    siteList.value = (res.data || []) as unknown as Site[];

    // 设置当前站点
    const userSiteId = userStore.userInfo?.siteId;
    const isSuperAdmin = userStore.userInfo?.role === "SUPER_ADMIN";

    if (userSiteId) {
      // 有站点ID，查找对应站点
      currentSite.value =
        siteList.value.find((s) => s.id === userSiteId) || null;
    } else if (isSuperAdmin) {
      // 超级管理员没有固定站点，默认选择"全部站点"
      currentSite.value = null;
    } else if (siteList.value.length > 0) {
      // 站点管理员如果没有siteId，默认使用第一个站点
      currentSite.value = siteList.value[0];
    }
  } catch (error) {
    console.error("加载站点列表失败:", error);
  }
};

// 切换站点
const handleSiteSwitch = async (siteId: number | null) => {
  try {
    if (siteId === null) {
      // 切换到全部站点
      currentSite.value = null;

      // 更新用户信息中的siteId（localStorage）
      if (userStore.userInfo) {
        const updatedUserInfo = { ...userStore.userInfo, siteId: null };
        userStore.setUserInfo(updatedUserInfo);
      }

      message.success("已切换到全部站点");
      window.location.reload();
    } else {
      const response = await switchSite(siteId);

      // 后端返回新的token，需要更新localStorage
      if (response.data) {
        const { token, siteName } = response.data;

        // 更新token
        localStorage.setItem("token", token);

        // 更新当前站点
        const site = siteList.value.find((s) => s.id === siteId);
        if (site) {
          currentSite.value = site;
        }

        // 更新用户信息中的siteId（localStorage）
        if (userStore.userInfo) {
          const updatedUserInfo = { ...userStore.userInfo, siteId };
          userStore.setUserInfo(updatedUserInfo);
        }

        message.success(`已切换到 ${siteName}`);

        // 刷新当前页面数据
        window.location.reload();
      }
    }
  } catch (error: any) {
    message.error(error.message || "切换站点失败");
  }
};

onMounted(() => {
  loadSites();
});

// 获取角色显示名称
const getRoleDisplayName = (role: string | undefined): string => {
  if (!role) return "";
  const roleMap: Record<string, string> = {
    PLATFORM_ADMIN: "平台超级管理员",
    SUPER_ADMIN: "超级管理员",
    SITE_ADMIN: "站点管理员",
  };
  return roleMap[role] || role;
};

// 账户信息
const handleProfile = () => {
  router.push("/profile");
};

// 退出登录
const handleLogout = () => {
  userStore.logout();
  message.success("退出登录成功");
  router.push("/login");
};
</script>

<style>
/* 确保body不限制宽度 */
body {
  overflow-x: auto !important;
  overflow-y: hidden !important; /* 禁止body的纵向滚动 */
  height: 100vh; /* 固定视口高度 */
}
</style>

<style scoped>
.main-layout {
  background: var(--bg-gray);
  min-width: 1200px; /* 整个页面最小宽度 */
  width: 100%; /* 正常情况下填满视口宽度 */
  height: 100vh; /* 占满视口高度 */
  max-height: 100vh; /* 最大不超过视口高度 */
  overflow: hidden; /* 不在这里产生滚动 */
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  gap: 40px;
  background: #fff;
  padding: 0 24px;
  border-bottom: 1px solid #e5e7eb;
  height: 64px;
  position: sticky;
  top: 0;
  z-index: 100;
  min-width: 1200px; /* header 最小宽度 */
}

.logo {
  flex-shrink: 0;
}

/* 顶部导航 */
.top-nav {
  flex: 1;
  display: flex;
  justify-content: start;
  align-items: center;
  gap: 4px;
  height: 64px;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 20px;
  height: 40px;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
  border-radius: 8px;
  cursor: pointer;
  transition: all var(--transition-fast);
  position: relative;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 40px;

  .logo-icon {
    font-size: 20px;
    color: var(--primary-color);
    margin-right: 6px;
  }

  .logo-text {
    font-size: 16px;
    font-weight: 600;
    color: #1f2937;
    white-space: nowrap;
  }
}

/* 顶部一级模块菜单 - 带图标的现代设计 */
.top-menu {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;

  .menu-item {
    position: relative;
    padding: 8px 16px;
    font-size: 14px;
    font-weight: 500;
    color: #65707e;
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    height: 36px;
    display: flex;
    align-items: center;
    gap: 6px;

    .menu-icon {
      font-size: 16px;
      color: inherit;
    }

    &:hover {
      color: var(--primary-color);
      background: rgba(99, 102, 241, 0.08);
      transform: translateY(-1px);
    }

    &.active {
      color: var(--primary-color);
      background: rgba(99, 102, 241, 0.12);
      font-weight: 600;
    }
  }
}

.nav-item:hover {
  color: var(--primary-color);
  background: var(--primary-light);
}

.nav-item.active {
  color: var(--primary-color);
  background: var(--primary-light);
}

.nav-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 24px;
  height: 3px;
  background: var(--primary-color);
  border-radius: 2px 2px 0 0;
}

.nav-icon {
  font-size: 16px;
}

.nav-label {
  white-space: nowrap;
  line-height: 1;
}

/* 右侧区域 */
.header-right {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 24px;
  color: var(--text-primary);
}

/* 站点信息 */
.site-info {
  display: flex;
  align-items: center;
}

.site-selector,
.site-display {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
}

.site-selector {
  cursor: pointer;
}

.site-icon {
  font-size: 14px;
  color: var(--primary-color);
}

.site-name {
  font-size: 13px;
  color: var(--text-primary);
  font-weight: 500;
}

.dropdown-icon-small {
  font-size: 10px;
  color: var(--text-tertiary);
}

/* 用户账户 */
.user-account {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 12px 6px 6px;
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
  cursor: pointer;
  border: 1px solid transparent;
}

/* .user-account:hover {
  background: var(--primary-light);
  border-color: var(--primary-color);
} */

.user-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  line-height: 1.3;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.user-role {
  font-size: 12px;
  color: var(--text-tertiary);
}

.dropdown-icon {
  font-size: 12px;
  color: var(--text-tertiary);
  transition: transform var(--transition-fast);
}

.user-account:hover .dropdown-icon {
  color: var(--primary-color);
  transform: translateY(2px);
}

.main-content-layout {
  display: flex;
  background: #f0f1f8 !important;
  height: calc(100vh - 64px); /* 固定高度 */
}

/* 二级功能菜单样式 (完全按参考项目) */
.primary-menu {
  position: relative;
  display: flex;
  width: 130px;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  height: calc(100vh - 64px); /* 固定高度 */
  padding-top: 17px;
  background: #f0f1f8;
  overflow-y: auto; /* 菜单项过多时滚动 */

  .primary-menu-item {
    display: flex;
    align-items: center;
    justify-content: end;
    width: 130px;
    height: 56px;
    color: #9097a7;
    cursor: pointer;

    .menu-item-title {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      width: 130px;
      height: 38px;
      padding: 0 24px;
      font-size: 14px;
      white-space: nowrap;
      border-radius: 30px 0 0 30px;
      font-family: PingFang SC, PingFang SC;

      .icon {
        font-size: 20px;
        color: #9097a7;
      }

      .menu-item-title__title {
        margin-left: 6px;
        font-size: 14px;
        line-height: 20px;
      }
    }

    &.active {
      .menu-item-title {
        background: #fff;
        color: #323233;

        .icon {
          color: var(--primary-color);
        }
      }
    }

    &:hover:not(.active) {
      .menu-item-title {
        background: rgba(255, 255, 255, 0.6);
      }
    }
  }
}

.sider {
  background: #fff;
  box-shadow: none;
  border-right: 1px solid #f0f0f0;
}

/* 三级子功能菜单样式 (完全按参考项目) */
.sub-menu {
  flex: 0 0 116px;
  box-sizing: border-box;
  width: 116px;
  height: calc(100vh - 64px); /* 固定高度 */
  padding-top: 24px;
  overflow: hidden;
  background: white;
  border-radius: 24px 0 0 0;

  .sub-menu-scroll {
    width: 116px;
    min-height: 100%; /* 改为最小高度 */
    overflow-y: auto;
    padding-left: 16px;
    box-sizing: border-box;
  }
}

:deep(.ant-layout-sider-children) {
  display: flex;
  flex-direction: column;
  padding-top: 8px;
}

/* 三级子功能菜单的Ant Design样式 (完全按参考项目) */
.sub-menu {
  :deep(.ant-menu-submenu-title:active) {
    background: none;
  }

  :deep(.ant-menu-inline .ant-menu-submenu) {
    padding-bottom: 6px;
  }

  :deep(.ant-menu-inline .ant-menu-submenu-title) {
    margin: 0;
    padding-right: 0;
  }

  :deep(.ant-menu-inline > .ant-menu-submenu > .ant-menu-submenu-title) {
    height: 42px;
    padding-left: 8px !important;
    line-height: 42px;
  }

  :deep(.ant-menu-sub.ant-menu-inline > .ant-menu-item) {
    display: block;
    height: 32px;
    font-size: 12px;
    line-height: 32px;
  }

  :deep(.ant-menu-inline .ant-menu-item) {
    margin: 5px 0;
    padding-left: 0 !important;
    padding-right: 0;
    width: 100%;
  }

  :deep(.ant-menu-sub.ant-menu-inline > .ant-menu-item) {
    margin-bottom: 8px;
    text-align: center;
  }

  :deep(
      .ant-menu-inline.ant-menu-root .ant-menu-item > .ant-menu-title-content
    ) {
    flex: 0 0 50%;
    width: 50%;
    padding: 0 7px;
    border-radius: 8px;
    color: #4d525c;
    font-weight: 400;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    line-height: 20px;
    white-space: nowrap;

    &:hover {
      color: #5c79f6;
    }
  }

  :deep(.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected) {
    background: none;

    &::after {
      display: none;
    }
  }

  :deep(
      .ant-menu:not(.ant-menu-horizontal)
        .ant-menu-item-selected
        > .ant-menu-title-content
    ) {
    color: var(--primary-color);
  }

  :deep(
      .ant-menu-light:not(.ant-menu-horizontal)
        .ant-menu-item:not(.ant-menu-item-selected):hover
    ) {
    background: none;
  }

  :deep(.ant-menu-sub.ant-menu-inline) {
    background: white;
  }

  :deep(.ant-menu-submenu-selected) {
    color: #2c2e31;
  }

  :deep(
      .ant-menu-inline.ant-menu-root
        .ant-menu-submenu-title
        > .ant-menu-title-content
    ) {
    color: #323233;
    font-weight: 500;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    letter-spacing: 0px;
    padding: 0 7px;
  }

  :deep(.ant-menu) {
    color: #4d525c;
    font-weight: 400;
    font-family: PingFang SC-Regular, PingFang SC;
    border-right: none;
    background: transparent;
  }

  :deep(.ant-menu-item:active) {
    background: none;
  }

  :deep(.ant-menu-submenu-arrow) {
    right: 0;
    color: #acb2c2;
    transform: translateY(1px);
  }

  :deep(
      .ant-menu-submenu-open.ant-menu-submenu-inline
        > .ant-menu-submenu-title
        > .ant-menu-submenu-arrow
    ) {
    transform: translateY(-2px);
  }

  :deep(
      .ant-menu-light:not(.ant-menu-horizontal) .ant-menu-submenu-title:hover
    ) {
    background: none;
  }
}

.content {
  flex: 1;
  min-width: 0; /* 防止flex子元素超出父容器 */
  height: calc(100vh - 64px); /* 固定高度 */
  overflow-y: auto; /* 内容过多时纵向滚动 */
  overflow-x: hidden; /* 不允许横向滚动 */
  background: transparent;
}

.content-wrapper {
  background: #fff;
  padding: 24px;
  border-radius: 24px 8px 8px 8px;
  height: 100%; /* 填充父容器高度 */
  box-sizing: border-box;

  /* 当没有三级菜单时，左上角圆角改为24px */
  .main-content-layout:not(:has(.sub-menu)) & {
    border-radius: 24px 0 0 0;
  }

  /* 当有三级菜单时，左上角圆角改为8px */
  .main-content-layout:has(.sub-menu) & {
    border-radius: 0;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.header-left {
  display: flex;
  flex: 1;
}
</style>
